#!/bin/sh /etc/rc.common
# Copyright (c) 2014 The Linux Foundation. All rights reserved.

. /lib/functions.sh
. /lib/functions/network.sh

START=50
IFPLUGD_ACTION=/etc/ifplugd/ifplugd.action
IFPLUGD_HOTPLUG=/etc/hotplug.d/net/99-ifplugd

ifplugd_per_device () {
	local device


	config_get device "$1" device
	[ "$device" == "lo" ] && return
	/usr/bin/ifplugd -I -i $device -M -p -q -r $IFPLUGD_ACTION
}

start() {
    [ -e "$IFPLUGD_ACTION" ] || {
        mkdir -p $(dirname $IFPLUGD_ACTION)
        cat > $IFPLUGD_ACTION << 'EOF'
#!/bin/sh

. /lib/functions.sh
. /lib/functions/network.sh

interface=$1
action=$2

event () {
	local device

	config_get device "$1" device

	if [ "$device" == "$interface" ]; then
		ubus call network.interface.$1 $action
	fi
}

config_load network
config_foreach event interface
EOF
        chmod +x $IFPLUGD_ACTION
    }
    [ -e "$IFPLUGD_HOTPLUG" ] || {
        mkdir -p $(dirname $IFPLUGD_HOTPLUG)
        cat > $IFPLUGD_HOTPLUG << 'EOF'
#!/bin/sh

/etc/init.d/ifplugd restart
EOF
        chmod +x $IFPLUGD_HOTPLUG
    }

    config_load network
    config_foreach ifplugd_per_device interface
}

stop() {
    killall ifplugd
}
